import { nextTick, onMounted, onUnmounted, unref } from "vue"
import echarts from "@/utils/lib/echarts"
import { SVGRenderer, CanvasRenderer } from "echarts/renderers"


export const RenderType = {
  SVGRenderer: 'SVGRenderer',
  CanvasRenderer: 'CanvasRenderer'
}
export const ThemeType = {
  Light: 'light',
  Dark: 'dark',
  Default: 'default'
}



export default function useChart(
  elRef,
  option
) {
  const { render, theme, autoChartSize, animation } = option || {
    render: RenderType.CanvasRenderer,
    autoChartSize: false,
    animation: {},
    theme: ThemeType.Default,
  }
  // 渲染模式
  echarts.use(render === RenderType.SVGRenderer ? SVGRenderer : CanvasRenderer)
  // echart实例
  let chartInstance = null

  // 初始化echart
  const initCharts = () => {
    const el = unref(elRef)
    console.log('el: ', el);
    if (!el || !unref(el)) {
      return
    }
    chartInstance = echarts.init(el, theme)
    window.chartInstance = chartInstance
  }

  // 更新/设置配置
  function setOption(option, opts = false, lazyUpdate = false) {
    console.log('opts: ', opts);
    nextTick(() => {
      if (!chartInstance) {
        initCharts()
        if (!chartInstance) return
      }
      if (typeof opts === 'boolean') {
        chartInstance.setOption(option, opts, lazyUpdate)
      } else if (typeof opts === 'object') {
        chartInstance.setOption(option, opts)
      }
    })
  };

  // 获取echart实例
  function getInstance() {
    if (!chartInstance) {
      initCharts()
    }
    console.log('chartInstance: ', chartInstance);

    return chartInstance
    
  }

  // 更新大小
  function resize() {
    chartInstance?.resize()
  }

  // 监听元素大小
  function watchEl() {
    // 给元素添加过渡
    if (animation?.enable) {
      let styles = animation?.styles ?? {}
      for (let key in styles) {
        elRef.value.style[key] = styles[key]
      }
    }
    const resizeObserver = new ResizeObserver((entries) => resize())
    resizeObserver.observe(elRef.value)
  }

  // 显示加载状
  function showLoading() { 
    if (!chartInstance) {
      initCharts()
    }
    chartInstance?.showLoading('default', {
      text: '正在加载',
      color: '#c23531',
      maskColor: 'rgba(255, 255, 255, 0.6)',
    })
  }
  // 显示加载状
  function hideLoading() {
    if (!chartInstance) {
      initCharts()
    }
    chartInstance?.hideLoading()
  }

  function disposeCharts (theme) {
    if (!chartInstance) {
     return
    }
    chartInstance.dispose()
  }

  onMounted(() => {
    window.addEventListener("resize", resize)
    // if (autoChartSize) watchEl()
  })

  onUnmounted(() => {
    window.removeEventListener("resize", resize)
  })

  return {
    initCharts,
    setOption,
    getInstance,
    showLoading,
    hideLoading,disposeCharts
  }
}
